package com.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.erp.annotation.Permission;
import com.erp.dto.CountResult;
import com.erp.dto.TokenData;
import com.erp.dto.UserVo;
import com.erp.pojo.User;
import com.erp.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@CrossOrigin
public class UserController {

    public static Map<String, TokenData> map = new ConcurrentHashMap<>();

    @Autowired
    private UserService userService;

    /*处理用户信息分页查询氢气*/
    @GetMapping("/userList")
    public Map<String,Object> userList(
        @RequestParam(defaultValue = "1") Integer pageNum
        ,@RequestParam(defaultValue = "3") Integer pageSize){
        return userService.queryUserListService(pageNum,pageSize);
    }

    //添加用户信息
    @PostMapping("/addUser")
    public Map<String,Object> addUser( @RequestBody User user){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败......");
        try{
            userService.save( user);
            result.put("code",200);
            result.put("msg","添加管理员成功......");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }


    @GetMapping("/delUser")
    public Map<String,Object> delUser( Integer id){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败......");
        try{
            userService.removeById( id);
            result.put("code",200);
            result.put("msg","删除用户成功......");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    /*处理用户信息更新请求*/
    @PostMapping("/updateUser")
    public Map<String,Object> updateUser(@RequestBody User user){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败......");
        try{
            userService.updateById(user);
            result.put("code",200);
            result.put("msg","更新用户信息成功.......");
        }catch(Exception ex){
            ex.printStackTrace();

        }
        return result;
    }

    @Permission(role ="统计管理员，超级管理员")
    /*处理员工年龄分部统计请求*/
    @GetMapping("/countEmpAge")
    public List<CountResult> countEmpAge(){
        return userService.countEmployeeAageService();
    }
    @Permission(role ="统计管理员，超级管理员")
    /*处理员工学历分布统计的请求*/
    @GetMapping("/countEmpEdu")
    public List<CountResult> countEmpEdu(){
        return userService.countEmployeeEduService();
    }


    /*处理用户登录请求*/
    @PostMapping("/userLogin")
    public Map<String,Object> userLogin(@Validated @RequestBody UserVo user, HttpSession session){
        Map<String,Object> result=new HashMap<>();
        result.put("code",400);
        result.put("msg","操作失败......");
        try{
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.select("uname","upwd","id")
                .eq("uname",user.getUname());
            User dbUser = userService.getOne(wrapper);
            if(dbUser!=null){
                //获得数据库查询到的用户对象
                if(dbUser.getUpwd().equals(user.getUpwd())){
                    //replace()：是字符串类（String）的一个方法，用于替换字符串中的字符或子字符串。
                    //"-"：表示要被替换的字符，这里是连字符。
                    //""：表示替换后的字符，这里是空字符串，即删除连字符。
                    String token = UUID.randomUUID().toString().replace("-", "");
                    result.put("code",200);
                    result.put("msg","登录成功......");

                    TokenData tokenData = new TokenData();
                    result.put("token", token);
                    tokenData.setUserId(dbUser.getId());
                    tokenData.setLastAccessTime(new Date());
//将一个键值对插入到map集合中：
//键是"token"。
//值是dbUser对象的id属性（通过getId()方法获取，并通过toString()转换为字符串）。
                    map.put(token, tokenData);
                }
            }

        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }



    @GetMapping("/logout")
    @ResponseBody
    public Map<String, Object> logout(HttpServletRequest request) {
        String auth =  request.getHeader("authorization");
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        UserController.map.remove(auth);
        result.put("msg", "退出成功");
        return result;
    }
}
